package cmdwin;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Properties;


public class Context {
	public static final String USERDATA_DOC = "doc";
	public static final String USERDATA_FILTER = "filter";
	
	private static Context context = null;

	private CommandWindow cmdwin=null;
	private HashMap userdata = new HashMap();
	private ICommand currCmd = null;   
	
	Context(CommandWindow w){
		this.cmdwin = w;
		context = this;
	}
	
	public static Context getInstance(){
		return context;
	}
	
	public CommandWindow getCommandWindow(){
		return cmdwin;
	}
	
	public synchronized Object getUserData(String id){
		return userdata.get(id);
	}
	
	public synchronized void setUserData(String id, Object data){
		userdata.put(id, data);
	}
	
	public ICommand getCommand(String id){
		return CommandWindow.cmdrun.get(id);
	}
	
	private static String[] getParams(String paramstr){
		return paramstr.split("[ ]+");
	}
	/**
	 * cmd:[param,...]
	 * @param cmdstr
	 */
	public void proccessCommand(String cmdstr){
		if(cmdstr==null || (cmdstr=cmdstr.trim()).isEmpty())
			return;
		String cmd;
		String[] params = null;
		int p=cmdstr.indexOf(':');
		if(p<0){
			cmd = cmdstr.toLowerCase();
		}else{
			cmd=cmdstr.substring(0,p).toLowerCase();
			params = getParams(cmdstr.substring(p+1));
		}
		currCmd = context.getCommand(cmd);
		if(currCmd!=null){
			try {
				if(params==null)
					params = new String[0];
				currCmd.execute(context, params);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public InputStream getCfgResource(String path){
		InputStream input = null;
		try{
			try{
				URL url = System.class.getResource(path);
				if(url!=null)
					input = url.openStream();
			}catch(Exception ex){
				ex.printStackTrace();
			}catch(Throwable tx){
				tx.printStackTrace();
			}
			if(input==null)
				input = new FileInputStream(new File(new File(System.getProperty("user.dir")),path));
			
		}catch(Exception e){
			e.printStackTrace();
		}catch(Throwable t){
			t.printStackTrace();
		}
		return input;
	}
	
	public Properties loadProperties(String entry){
		InputStream ins = getCfgResource("/config/"+entry + ".properties");
		Properties prop = new Properties();
		try {
			prop.load(ins);
			ins.close();
		} catch (Exception e) {			
			e.printStackTrace();
		}
		return prop;
	}
	
	public void storeProperties(Properties prop, String entry){
		try {
			FileOutputStream fos = new FileOutputStream(new File(new File(System.getProperty("user.dir")),"/config/"+entry + ".properties"));
			prop.store(fos, null);		
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
